var call = require("../../utils/request.js")
import qqmap from '../../utils/map.js';
Page({
  data: {
    showloading :false,
    winHeight: 0,
    //下面是字母排序
    letter: ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"],
    cityListId: '',
    //下面是城市列表信息
    citylist: [],
    //下面是热门城市数据，模拟数据
    // newcity: ['北京', '上海', '广州', '深圳', '成都', '杭州'],
    // citySel: '全国',
    locateCity: ''
  },

  //点击城市
  cityTap(e) {
    console.log(e)
    const val = e.currentTarget.dataset.val || '',
      types = e.currentTarget.dataset.types || '',
      Index = e.currentTarget.dataset.index || '',
      that = this;
    switch (types) {
      case 'locate':
        //定位内容
        city = this.data.locateCity;
        break;
      case 'list':
        //城市列表
        city = val.cityName;
        break;
    }
    if (city) {
      wx.setStorage({
        key: 'city',
        data: city
      })
      //点击后给父组件可以通过bindcitytap事件，获取到cityname的值，这是子组件给父组件传值和触发事件的方法
      this.triggerEvent('citytap', { cityname: city });
    } else {
      console.log('还没有');
      this.getLocate();
    }
    const cityName = e.detail.cityname;
    wx.navigateBack();
  },
  //点击城市字母
  letterTap(e) {
    const Item = e.currentTarget.dataset.item;
    this.setData({
      cityListId: Item
    });
    console.log("..............." + this.data.cityListId);
  },
  //调用定位
  getLocate() {
    let that = this;
    new qqmap().getLocateInfo().then(function (val) {//这个方法在另一个文件里，下面有贴出代码
      console.log(val);
      if (val.indexOf('市') !== -1) {//这里是去掉“市”这个字
        console.log(val.indexOf('市') - 1);
        val = val.slice(0, val.indexOf('市'));
        console.log(val);
      }
      that.setData({
        locateCity: val
      });
      //把获取的定位和获取的时间放到本地存储
      wx.setStorageSync('locatecity', { city: val, time: new Date().getTime() });
    });
  },

  onLoad: function (options) {
    const that = this;
    const win = wx.getSystemInfoSync();
    this.setData({
      winHeight: win.windowHeight,
      locateCity:options.locateCity
    });

    call.getData('area/locationByFirstWord', {}, this.getWord, this.fail);
  },
  onReady:function(){

  },
  getWord: function (data) {
    var that = this;
    that.setData({
      citylist: data
    })
    this.data.showloading = true;
  },
  fail: function () {
    console.log("失败")
  },
  onShow() {
    let that = this,
      cityOrTime = wx.getStorageSync('locatecity') || {},
      time = new Date().getTime(),
      city = '';
    if (!cityOrTime.time || (time - cityOrTime.time > 1800000)) {//每隔30分钟请求一次定位
      this.getLocate();
    } else {//如果未满30分钟，那么直接从本地缓存里取值
      that.setData({
        locateCity: cityOrTime.city
      })
    }
  }
})

